using UnityEngine;
using System.Collections;

[RequireComponent(typeof(CharacterController))]

public class CharControl : MonoBehaviour {
	CharacterController controller;
	bool Running = false;
	float Speed = 2.0f;
	
	//Animations
	public AnimationClip Idle;
	public AnimationClip Walk;
	public AnimationClip Run;
	public AnimationClip Jump;

	void Start ()
	{
		controller = GetComponent<CharacterController>();

		animation.AddClip(Idle, "Idle");
		animation.AddClip(Walk, "Walk");
		animation.AddClip(Run, "Run");
		animation.AddClip(Jump, "Jump");
	}

	void Update ()
    {
        transform.RotateAround(Vector3.up, Input.GetAxis("Horizontal") / 20.0f);

        if (Input.GetAxis("Vertical") > 0)
        {
            controller.SimpleMove(transform.forward * Input.GetAxis("Vertical") * Speed);

            if (Running)
                animation.CrossFade("Run");
            else
                animation.CrossFade("Walk");
        }
        else
            animation.CrossFade("Idle");

		
		if (Input.GetKeyDown(KeyCode.LeftShift))
		{
			Speed += 2.0f;
			Running = true;
		}
		if (Input.GetKeyUp(KeyCode.LeftShift))
		{
			Speed -= 2.0f;
			Running = false;
		}
		
		ControllAudio();
	}

    bool Playing = false;	
	void ControllAudio()
	{
		audio.pitch = 1.2f;
		if (Running)
			audio.pitch = 2.5f;

        if (Input.GetAxis("Vertical") > 0 && !Playing)
        {
            audio.PlayDelayed(-2.0f);
            Playing = !Playing;
        }
        if (Input.GetAxis("Vertical") <= 0 && Playing)
        {
            audio.Stop();
            Playing = !Playing;
        }
	}
}